package com.jzo2o.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.ActivityTypeEnum;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.CouponWriteOff;
import com.jzo2o.market.model.dto.request.ActivityQueryForPageReqDTO;
import com.jzo2o.market.model.dto.request.ActivitySaveReqDTO;
import com.jzo2o.market.model.dto.response.ActivityInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    private static final int MILLION = 1000000;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ICouponService couponService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;


    //新增优惠劵活动
    @Override
    public void saveActivity(ActivitySaveReqDTO activitySaveReqDTO) {
        Activity activity = this.getById(activitySaveReqDTO.getId());

        if (!BeanUtil.isEmpty(activity)){
            //如果不是满减就设置满减金额为0
            if (!activitySaveReqDTO.getType().equals(ActivityTypeEnum.AMOUNT_DISCOUNT.getType())){
                activity.setDiscountAmount(BigDecimal.valueOf(0));
            }
            //进行复制
            BeanUtil.copyProperties(activitySaveReqDTO,activity);

            activity.setStockNum(activitySaveReqDTO.getTotalNum());

            //得到状态
            Integer status = comprateDate(activitySaveReqDTO);
            activity.setStatus(status);
            activity.setUpdateBy(UserContext.currentUserId());
            boolean update = this.updateById(activity);
            if (!update){
                throw new BadRequestException("修改失败");
            }
            return;
        }

        Activity activity1 = BeanUtils.copyBean(activitySaveReqDTO, Activity.class);
        Integer status = comprateDate(activitySaveReqDTO);
        activity1.setStatus(status);
        activity1.setStockNum(activitySaveReqDTO.getTotalNum());
        activity1.setUpdateBy(UserContext.currentUserId());
        activity1.setCreateBy(UserContext.currentUserId());
        boolean save = this.save(activity1);
        if (!save){
            throw new BadRequestException("新增失败");
        }

    }

    //比较时间
    private Integer comprateDate(ActivitySaveReqDTO activitySaveReqDTO){
        Integer status = 3;
        if (activitySaveReqDTO.getDistributeStartTime().isAfter(LocalDateTime.now())){
            status= ActivityStatusEnum.NO_DISTRIBUTE.getStatus();
        }else if(activitySaveReqDTO.getDistributeStartTime().isBefore(LocalDateTime.now())&& activitySaveReqDTO.getDistributeEndTime().isAfter(LocalDateTime.now())) {
            status= ActivityStatusEnum.DISTRIBUTING.getStatus();
        }
        return status;
    }


    //运营端优惠劵活动分页查询
    @Override
    public PageResult<ActivityInfoResDTO> activityPage(ActivityQueryForPageReqDTO activityQueryForPageReqDTO) {
        // 1. 获取分页对象
        Page<Activity> ordersPage = PageUtils.parsePageQuery(activityQueryForPageReqDTO, Activity.class);
        // 2. 执行内置分页方法
        LambdaQueryWrapper<Activity> wrapper = Wrappers.<Activity>lambdaQuery()
                .orderByDesc(Activity::getCreateTime)
                .eq(activityQueryForPageReqDTO.getType() != null, Activity::getType, activityQueryForPageReqDTO.getType())
                .eq(activityQueryForPageReqDTO.getStatus() !=null, Activity::getStatus, activityQueryForPageReqDTO.getType())
                .like(activityQueryForPageReqDTO.getId()!=null,Activity::getId,activityQueryForPageReqDTO.getId())
                .like(StringUtils.isNotBlank(activityQueryForPageReqDTO.getName()),Activity::getName,activityQueryForPageReqDTO.getName());
        Page<Activity> page = this.page(ordersPage, wrapper);
        // 3. 封装分页结果
        return PageUtils.toPage(page, ActivityInfoResDTO.class);
    }



    //根据id查询优惠劵活动的具体id
    @Override
    public ActivityInfoResDTO getActivityById(Long id) {

        Activity activity = this.getById(id);
        ActivityInfoResDTO activityInfoResDTO = BeanUtil.copyProperties(activity, ActivityInfoResDTO.class);
        Integer receiveNum = activity.getTotalNum()- activity.getStockNum();
        activityInfoResDTO.setReceiveNum(receiveNum);
        //核销数量
        Integer writeOffNum = couponWriteOffService.lambdaQuery().eq(CouponWriteOff::getActivityId, id).count();
        activityInfoResDTO.setWriteOffNum(writeOffNum);

        return activityInfoResDTO;
    }

    //定时任务
    @Override
    public void updateStatus() {
        LocalDateTime now = LocalDateTime.now();

        //修改活动表进行中
        boolean update = this.lambdaUpdate().lt(Activity::getDistributeStartTime, now)
                .ge(Activity::getDistributeEndTime, now)
                .set(Activity::getStatus, ActivityStatusEnum.DISTRIBUTING.getStatus())
                .update();
        //已结束
        boolean update1 = this.lambdaUpdate().lt(Activity::getDistributeEndTime, now)
                .set(Activity::getStatus, ActivityStatusEnum.LOSE_EFFICACY.getStatus())
                .update();
    }
}
